﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Web.UserControls;
using Telerik.Web.UI;
using BSCMFF.Core.Exceptions.Database;

namespace BSCMFF.Web.Pages.Evaluation_Setup.Personalist
{
    public partial class EvaluationEditMode : BSCMFF.Core.MultiLanguagePage
    {
        private static int categories = 0;

        public int Categories 
        { 
            get
            {
                return categories;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (Request.QueryString["EvaluationID"] != null)
                {
                    int evalID = Convert.ToInt32(Request.QueryString["EvaluationID"]);


                    BSCEntities context = new BSCEntities();
                    Evaluation_Period selectedEval = (from ev in context.Evaluation_Period
                                                      where ev.ID == evalID
                                                      select ev).SingleOrDefault();
                    ed.Evalut = selectedEval;
                    ed.DataBind();

                    LoadCategories(evalID);

                    CheckBoxPKPIs.Checked = selectedEval.PKPIs.Value;
                    CheckBoxCompetencies.Checked = selectedEval.Competencies.Value;
                    CheckBoxReward.Checked = selectedEval.Reward.Value;
                    RadButtonCreateTypes_Click(sender, e);
                    LoadEvalProperties(selectedEval);
                    //LoadUsers(evalID);

                    RadButtonCancel.Text = "Back";
                    RadButtonDelete.Visible = true;
                }
                else
                {
                    CreateCategory2(); //RadButtonAddCategory_Click(sender, new EventArgs());
                    RadButtonDelete.Visible = false;
                    //categories = 1;
                }
                RadButtonSave.Visible = true;
                //RadButtonCreate
                //RadButtonUpdate.Visible = false;
                
            }

            //if (IsPostBack)
            //{
            //    //PersistDynamicCategories();
            //}
            //else
            //{
            //    if (Request.QueryString["EvaluationID"] == null)
            //    {
            //        categories = 1;
            //    }
            //}
        }

        

        protected void RadButtonCreateTypes_Click(object sender, EventArgs e)
        {

            PlaceHolderParts.Visible = true;
            PlaceHolderInterviewPart.Visible = true;

            if (CheckBoxReward.Checked && !CheckBoxPKPIs.Checked && !CheckBoxCompetencies.Checked)
            {
                LabelRewardWarning.Visible = true;
                return;
            }
            LabelRewardWarning.Visible = false;
            PlaceHolderPKPIsPart.Visible = CheckBoxPKPIs.Checked;
            PlaceHolderCompetenciesPart.Visible = CheckBoxCompetencies.Checked;
            PanelRewardCompetenciesSetting.Visible = CheckBoxCompetencies.Checked;
            PlaceHolderRewardPart.Visible = CheckBoxReward.Checked;

            //PanelRewardPKPISettings.Visible = CheckBoxPKPIs.Checked;
            //PanelRewardCompetenciesSetting.Visible = CheckBoxCompetencies.Checked;
            
            RadButtonCreateTypes.Text = "Update";            
        }
        
        protected void RadButtonAddCategory_Click(object sender, EventArgs e)
        {
            CreateCategory2();

            CreateCategoryButtonVisibility();

            DeleteCategoryButtonVisibility();
        }

        private void CreateCategoryButtonVisibility()
        {
            if (categories >= 9)
            {
                RadButtonSave.Visible = false;
            }
            else
            {
                RadButtonSave.Visible = true;
            }
        }

        protected void RadButtonDeleteCategory_Click(object sender, EventArgs e)
        {
            EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)PlaceHolderCategories.FindControl("EvaluationQuestionCategory" + (--categories).ToString());
            eqc.Visible = false;
            eqc.EnableViewState = false;

            DeleteCategoryButtonVisibility();
        }

        private void DeleteCategoryButtonVisibility()
        {
            if (categories <= 0)
            {
                RadButtonDeleteCategory.Visible = false;
            }
            else
            {
                RadButtonDeleteCategory.Visible = true;
            }
        }

       /*private void CreateCategory()
        {
            Control c = LoadControl("~/UserControls/EvaluationQuestionCategory.ascx");

            c.ID = "EQC" + categories++.ToString();

            //((EvaluationQuestionCategory)c).PublicEQ.NumQuestions = Int32.Parse(HiddenFieldCurrentNumQuestions.Value); // EQC0.PublicEQ.NumQuestions;

            PlaceHolderCategories.Controls.Add(c);
        }*/

        private void CreateCategory2()
        {
            EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)PlaceHolderCategories.FindControl("EvaluationQuestionCategory" + (categories++).ToString());
            eqc.Visible = true;
            eqc.EnableViewState = true;
        }

        /*private void LoadUsers(int evalID)
        {
            BSCEntities context = new BSCEntities();

            List<User> users = (from eu in context.Evaluation_User.Include("User")
                                where eu.Evaluation_FK == evalID
                                select eu.User).ToList();

            //List<User> users = (from u in context.Users.Include("Evaluation_User")
            //                    where u.Evaluation_User.fi FirstOrDefault().Evaluation_FK == evalID
            //                    select u).ToList();

            foreach(User user in users)
            {
                //EGS.RadListBoxSelectedEmployees.Items.Add(new RadListBoxItem(user.Fullname, user.ID.ToString()));
            }
        }*/

        private void LoadCategories(int evalID)
        {
            BSCEntities context = new BSCEntities();

            List<Evaluation_Category> cats = (from c in context.Evaluation_Category
                                              where c.Evaluation_FK == evalID
                                             // orderby c.ID descending
                                              select c).ToList();
            categories = 0;
            foreach (Evaluation_Category cat in cats)
            {
                /*EvaluationQuestionCategory eqc = LoadControl("~/UserControls/EvaluationQuestionCategory.ascx") as EvaluationQuestionCategory;
                eqc.ID = "EQC" + categories; //cat.ID.ToString();
                eqc.CategoryName = cat.Name;
                eqc.IsEditMode = true;
                */
                EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)PlaceHolderCategories.FindControl("EvaluationQuestionCategory" + (categories++).ToString());
                eqc.CategoryName = cat.Name;
                eqc.IsEditMode = true;
                eqc.Visible = true;

                List<Evaluation_Question> equestions = (from eq in context.Evaluation_Question
                                                        where eq.Evaluation_Category_FK == cat.ID
                                                        
                                                        select eq).ToList();

                eqc.SavedQuestions = equestions;
                eqc.Min = cat.Min;
                eqc.Max = cat.Max;

                //    PlaceHolderCategories.Controls.AddAt(categories++, eqc);

                /*
                //eqc.SetQuestionsProperties(cat.NumberOfQuestions, cat.Min, cat.Max);
                eqc.CreateQuestion(); //PublicEQ.CreateQuestionLoad(cat.NumberOfQuestions, cat.Min, cat.Max);
                //eqc.PublicEQ.Visible = true;
               // ((Control)eqc.FindControl("RadButtonCreateCategory")).Visible=false;
                Panel pq = eqc.PublicPanelQuestions;
               // pq.Visible = true;
                int i = 0;
                foreach (Evaluation_Question equestion in equestions)
                {
                    RadTextBox rquestion = pq.FindControl("Question" + i.ToString()) as RadTextBox;
                    rquestion.Text = equestion.Question;
                    ++i;
                }
                //EQC0.ID = "Question" + i.ToString();
                */
            
                
            }
            //RadButtonAddCategory_Click(this, new EventArgs());
        }

        

        /*private void PersistDynamicCategories()
        {
            for (int i = 0; i < categories; ++i)
            {
                Control c = LoadControl("~/UserControls/EvaluationQuestionCategory.ascx");

                c.ID = "EQC" + i.ToString();

                //((EvaluationQuestionCategory)c).EventAddCategory += AddCategory;

                if (categories == 1)//stupid
                {
                   // ((EvaluationQuestionCategory)c).RadButtonUpdateQuestions_Click(this, new EventArgs());
                }
                PlaceHolderCategories.Controls.Add(c);
               // c.Focus();
            }
        }*/


        

        //private void SaveCategoryQuestions()
        //{
        //    BSCEntities context = new BSCEntities();


        //    foreach (Control c in PlaceHolderCategories.Controls)
        //    {
        //        if(c.GetType() == typeof(EvaluationQuestionCategory))
        //        {
        //            //Evaluation_Category ec = 
        //        }
        //    }
        //}

        #region CreateEvalution

        //protected void SaveEvaluation()
        //{
        //    BSCEntities context = new BSCEntities();

        //    Evaluation_Period ev = ed.Evalut;

        //    Evaluation_Period saveEV = (from eval in context.Evaluation_Period
        //                                where eval.ID == ev.ID
        //                                select eval).SingleOrDefault();

        //    saveEV.Name = ev.Name;
        //    saveEV.Description = ev.Description;
        //    saveEV.StartDate = ev.StartDate;
        //    saveEV.EndDate = ev.EndDate;
        //    saveEV.Repetition = ev.Repetition;

        //    SaveCategoryQuestions();

        //    try
        //    {
        //        context.SaveChanges();
        //    }
        //    catch (Exception e)
        //    {
        //        throw new InconsistentDatabaseException("Couldn't save Evaluation Period: " + e.Message);
        //    }
        //}

        protected void SaveEvaluation(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                //RadButtonCreate.Visible = false;
                //RadButtonUpdate.Visible = true;
                //radbuttonde

                BSCEntities context = new BSCEntities();

                Evaluation_Period ev = ed.Evalut;

                Evaluation_Period eval = (from evaluation in context.Evaluation_Period
                                          where evaluation.ID == ev.ID
                                          select evaluation).SingleOrDefault();

                if (eval == null)
                {
                    setEvalProperties(ev);

                    context.AddToEvaluation_Period(ev);
                }
                else
                {
                    eval.Name = ed.Evalut.Name;
                    eval.Description = ed.Evalut.Description;
                    eval.StartDate = ed.Evalut.StartDate;
                    eval.EndDate = ed.Evalut.EndDate;
                    //eval.Name = ev.Name;
                    //eval.Description = ev.Description;
                    //eval.StartDate = ev.StartDate;
                    //eval.EndDate = ev.EndDate;
                    //eval.Repetition = ev.Repetition;
                    //eval.Interview = PlaceHolderInterviewPart.Visible;
                    //eval.PKPIs = PlaceHolderPKPIsPart.Visible;
                    //eval.Competencies = PlaceHolderCompetenciesPart.Visible;
                    setEvalProperties(eval);
                }

                try
                {
                    context.SaveChanges();
                    if (eval != null)
                    {
                        DeleteAllEvaluationObjects(eval.ID);
                        //context.DeleteObject(eval);
                    }

                    CreateCategoryQuestions(ev.ID);
                    //ConnectEvalautionWithEmployees(ev.ID, EGS.RadListBoxSelectedEmployees.Items);
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't save evaluation: " + ex.Message);
                }

                RadButtonCancel.Text = "Back";
                //Response.Redirect("EvaluationEditMode.aspx?EvaluationID=" + ev.ID);

                Response.Redirect("EvaluationList.aspx?EvaluationID=" + ev.ID);
            }
        }

        private void setEvalProperties(Evaluation_Period ev)
        {
            ev.Interview = PlaceHolderInterviewPart.Visible;
            ev.PKPIs = PlaceHolderPKPIsPart.Visible;
            ev.Competencies = PlaceHolderCompetenciesPart.Visible;
            ev.Reward = PlaceHolderRewardPart.Visible;

            if (ev.PKPIs == true)
            {
                //pkpi scale
                ev.To1 = (int?)RadNumericTextBoxTo1.Value;
                ev.Verbal1 = RadTextBoxVerbal1.Text;
                ev.From2 = (int?)RadNumericTextBoxFrom2.Value;
                ev.To2 = (int?)RadNumericTextBoxTo2.Value;
                ev.Verbal2 = RadTextBoxVerbal2.Text;
                ev.From3 = (int?)RadNumericTextBoxFrom3.Value;
                ev.To3 = (int?)RadNumericTextBoxTo3.Value;
                ev.Verbal3 = RadTextBoxVerbal3.Text;
                ev.From4 = (int?)RadNumericTextBoxFrom4.Value;
                ev.To4 = (int?)RadNumericTextBoxTo4.Value;
                ev.Verbal4 = RadTextBoxVerbal4.Text;
                ev.From5 = (int?)RadNumericTextBoxFrom5.Value;
                ev.Verbal5 = RadTextBoxVerbal5.Text;
            }
            //revard
            if (ev.Reward == true)
            {
                //ev.TestOnly = CheckBoxTestOnly.Checked;
                //ev.PKPIFromScore = (int?)RadNumericTextBoxPKPIsFrom.Value;
                //ev.PKPIMinCoef = (int?)RadNumericTextBoxMinCoef.Value;
                //ev.PKPIMaxCoef = (int?)RadNumericTextBoxMaxCoef.Value;
                if (ev.Competencies == true)
                {
                    ev.CompetencyTop = (int?)RadNumericTextBoxCompetencyTop.Value;
                }
                //ev.CompetencyCoef = (int?)RadNumericTextBoxCompetencyCoef.Value;

                if (ev.PKPIs == true)
                {
                    ev.SigmoidA = BonusSigmoid1.PublicValueA;
                    ev.SigmoidB = BonusSigmoid1.PublicValueB;
                }
                if (ev.Competencies==true && ev.PKPIs==true)
                {
                    ev.BonusSliderValue = BonusSettings1.Value;
                }
                ev.TotalBonus = (decimal)RadNumericTextBoxTotalBonus.Value;
            }
        }

        private void LoadEvalProperties(Evaluation_Period ev)
        {
            if (ev.PKPIs == true)
            {
                //pkpi scale
                RadNumericTextBoxTo1.Value = ev.To1;
                RadTextBoxVerbal1.Text = ev.Verbal1;
                RadNumericTextBoxFrom2.Value = ev.From2;
                RadNumericTextBoxTo2.Value = ev.To2;
                RadTextBoxVerbal2.Text = ev.Verbal2;
                RadNumericTextBoxFrom3.Value = ev.From3;
                RadNumericTextBoxTo3.Value = ev.To3;
                RadTextBoxVerbal3.Text = ev.Verbal3;
                RadNumericTextBoxFrom4.Value = ev.From4;
                RadNumericTextBoxTo4.Value = ev.To4;
                RadTextBoxVerbal4.Text = ev.Verbal4;
                RadNumericTextBoxFrom5.Value = ev.From5;
                RadTextBoxVerbal5.Text = ev.Verbal5;
            }
            if (ev.Reward == true)
            {
                //CheckBoxTestOnly.Checked = (bool)ev.TestOnly;
                //RadNumericTextBoxPKPIsFrom.Value = ev.PKPIFromScore;
                //RadNumericTextBoxMinCoef.Value = ev.PKPIMinCoef;
                //RadNumericTextBoxMaxCoef.Value = ev.PKPIMaxCoef;
                if (ev.Competencies == true)
                {
                    RadNumericTextBoxCompetencyTop.Value = ev.CompetencyTop;
                }
                //RadNumericTextBoxCompetencyCoef.Value = ev.CompetencyCoef;
                if (ev.PKPIs == true)
                {
                    BonusSigmoid1.PublicValueA = (double)ev.SigmoidA;
                    BonusSigmoid1.PublicValueB = (double)ev.SigmoidB;
                }
                if (ev.Competencies == true && ev.PKPIs == true)
                {
                    BonusSettings1.Value = (int)ev.BonusSliderValue;
                }
                RadNumericTextBoxTotalBonus.Value = (double)ev.TotalBonus;
            }
        }

        private void DeleteAllEvaluationObjects(int eval_ID)
        {
            BSCEntities context = new BSCEntities();

            //var questions = (from q in context.Evaluation_Question.Include("Evaluation_Category")
            //                 where q.Evaluation_Category.Evaluation_FK == eval_ID
            //                 select q);
            //foreach (Evaluation_Question question in questions)
            //{
            //    context.DeleteObject(question);
            //}

            var categories = (from c in context.Evaluation_Category
                              where c.Evaluation_FK == eval_ID
                              select c);
            foreach (Evaluation_Category category in categories)
            {
                context.DeleteObject(category);
            }

            //var eval_users = (from eu in context.Evaluation_User
            //                  where eu.Evaluation_FK == eval_ID
            //                  select eu);
            //foreach (Evaluation_User eval_user in eval_users)
            //{
            //    context.DeleteObject(eval_user);
            //}

            try
            {
                context.SaveChanges();
            }
            catch (Exception e)
            {
                throw new InconsistentDatabaseException("Couldn't save evaluation: " + e.Message);
            }
        }

        //private void ConnectEvalautionWithEmployees(int eval_ID, RadListBoxItemCollection radListBoxItemCollectionUsers)
        //{
        //    BSCEntities context = new BSCEntities();

        //    foreach (RadListBoxItem ri in radListBoxItemCollectionUsers)
        //    {
        //        Evaluation_User eu = new Evaluation_User();
        //        eu.Evaluation_FK = eval_ID;
        //        eu.User_FK = Int32.Parse(ri.Value);

        //        context.AddToEvaluation_User(eu);
        //    }
        //    try
        //    {
        //        context.SaveChanges();
        //    }
        //    catch
        //    {
        //        throw new Exception();
        //    }
        //}

        private void CreateCategoryQuestions(int evalID)
        {
            BSCEntities context = new BSCEntities();

            foreach (Control c in PlaceHolderCategories.Controls)
            {
                if (c.GetType().BaseType.Name == "EvaluationQuestionCategory")
                {
                    EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)c;

                    if (eqc.CategoryName == "")
                    {
                        continue;
                    }
                    Evaluation_Category ec = new Evaluation_Category();
                    ec.Evaluation_FK = evalID;
                    ec.Name = eqc.CategoryName;

                    ec.NumberOfQuestions = eqc.NumberQuestions;
                    ec.Min = eqc.Min;
                    ec.Max = eqc.Max;

                    context.AddToEvaluation_Category(ec);
                    try
                    {
                        context.SaveChanges();
                        CreateQuestions(ec.ID, eqc.PublicPanelQuestions);
                    }
                    catch (Exception e)
                    {
                        throw new InconsistentDatabaseException("Couldn't save evaluation: " + e.Message);
                    }
                    
                }
            }
        }

        private void CreateQuestions(int categoryID, Panel evaluationQuestions)
        {
            BSCEntities context = new BSCEntities();

            Table t = (Table)evaluationQuestions.FindControl("TableQuestions");
            for (int i = 1; i < t.Rows.Count; ++i)
            {
                Evaluation_Question eq = new Evaluation_Question();
                eq.Question = ((RadTextBox)((t).Rows[i].Cells[0].Controls[0])).Text;
                eq.Evaluation_Category_FK = categoryID;

                context.AddToEvaluation_Question(eq);
            }

            try
            {
                context.SaveChanges();
                
            }
            catch (Exception e)
            {
                throw new InconsistentDatabaseException("Couldn't save evaluation: " + e.Message);
            }
        }

        #endregion

        protected void RadButtonCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManageEvaluations.aspx");
        }

        protected void RadButtonDelete_Click(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();
            var ep = (from eps in context.Evaluation_Period
                      where eps.ID == ed.Evalut.ID
                      select eps).SingleOrDefault();

            if (ep != null)
            {
                context.DeleteObject(ep);
            }

            try
            {
                context.SaveChanges();

            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't delete evaluation: " + ex.Message);
            }

            Response.Redirect("ManageEvaluations.aspx");
        }
    }
}